<meta charset="UTF-8">
<?php
require ('./lib/init.php');
$sql = "select * from cat";
$cats = mGetAll($sql);
if (empty($_POST)){
    include (ROOT . '/view/admin/artadd.html');
}else{
//    检测标题是否为空
    $art['title'] = trim($_POST['title']);
    if ($art['title'] == ''){
        error('标题不能为空');
    }

//     判断是否有图片上传 且 Error 是否 为 0
    if (!empty($_FILES['pic']['name'])  &&  ($_FILES['pic']['error'] == 0)){
        $ext = getExt($_FILES['pic']['name']);
            //后端判断后缀
        if (($ext == '.jpg') or ($ext == '.png') or ($ext == '.jpeg')) {
            $filename = createDir() . '/' . randStr() . getExt($_FILES['pic']['name']);
            if (move_uploaded_file($_FILES['pic']['tmp_name'], ROOT . $filename)) {
                $art['pic'] = $filename;
                $art['thumb'] = makeThemb($filename);
            }//上传文件到指定目录
        }
        else{
            error('文件后缀不匹配！只支持jpg/png/jpeg');
        }
    }

//    检测栏目是否合法
    $art['cat_id']= $_POST['cat_id'];
    if (!is_numeric($art['cat_id'])){
        error('栏目不合法！');
    }
//    检测内容是否为空
    $art['content'] = trim($_POST['content']);
    if ($art['content'] == ''){
        error('内容不能为空！');
    }

//    检测作者是否为空
    $art['author'] = trim($_POST['author']);
    if ($art['author'] == ''){
        error('作者不能为空！');
    }
//    插入发布时间
    $art['pubtime'] = time();

//    收集tag
   $art['arttag'] = trim($_POST['tag']);
//    执行发布操作
    if (!mExec('art',$art)){
        error('文章发布失败！');
    }{
//        判断tag是否存在
        $art['tag'] = trim($_POST['tag']);
        if ($art['tag'] == ''){
            //cat 表的文章数量+1
            $sql = "update cat set cat_num = cat_num + 1 where cat_id = $art[cat_id]";
            mQuery($sql);
            succ('文章发布成功！');
        }else{
            $art_id = getLastId();
//            插入tag到表
            $tag = explode(',',$art['tag']);
            $sql = "insert into tag (art_id,tag) values  ";
            foreach ($tag as $v){
            $sql .= "(" . $art_id . ",' " . $v . "'),";
            }
            $sql = rtrim($sql,",");
            if (mQuery($sql)){
                //cat 表的文章数量+1
                $sql = "update cat set cat_num = cat_num + 1 where cat_id = $art[cat_id]";
                mQuery($sql);
                succ('文章添加成功');
            }else{
//                tag 添加失败
                $sql = "delete from art where art_id = $art_id";
                if(mQuery($sql)){
                    //cat 表的文章数量-1
                    $sql = "update cat set cat_num = cat_num - 1 where cat_id = $art[cat_id]";
                    mQuery($sql);
                    error ('文章添加失败');
                }else{
                    error('服务器出错！');
                }
            }
        }
    }
}


?>